<?php

namespace app\controller;

use app\BaseController;
use app\common\CacheKey;
use app\common\Sms;
use app\facade\ConnectDbFacade;
use app\models\user\ProgramInfoModel;
use app\models\user\ProgramProductModel;
use app\models\user\UserModel;
use app\services\utils\RedisService;
use app\services\utils\TokenService;
use app\services\utils\AmapService;
use app\services\utils\SmsService;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use think\Request;


class IndexController extends BaseController
{

    /**
     * 默认访问
     * @return string
     */
    public function index()
    {
        return 'hello,world';
    }

    public function test()
    {
        try {
            $value = 111;
            $value = json_encode($value);
            var_dump($value);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function clear()
    {
        try {
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 延迟队列
     */
    public function testQueue()
    {
        //当前任务将由哪个类来负责处理。
        //当轮到该任务时，系统将生成一个该类的实例，并默认调用其 fire 方法
        $jobHandlerClassName = 'app\job\OrderJob';

        //当前任务归属的队列名称，如果为新队列，会自动创建
        //php think queue:work --queue orderJobQueue
        //php think queue:work --queue orderJobQueue --daemon

        $jobQueueName = "orderJobQueue";

        //数组数据
        $orderData = ['id' => uniqid(), 'time' => time(), 'message' => 'later message83'];

        //将该任务推送到消息队列，等待对应的消费者去执行
        //这里只是负责将数据添加到相应的队列名称的队列里，消费者与生产者并无联系

        //立即执行
        //        $isPushed = Queue::push($jobHandlerClassName, $orderData, $jobQueueName);
        //延迟10秒后执行
        $isPushed = Queue::later(30, $jobHandlerClassName, $orderData, $jobQueueName);

        if ($isPushed !== false) {
            echo date('Y-m-d H:i:s') . " 队列添加成功";
        } else {
            echo '队列添加失败';
        }
    }

    /**
     * redis
     * @return \think\response\Json
     */
    public function testRedis()
    {
        $client = RedisService::instance();
        $client->set('test', 1111);
        $result = $client->get('test');
        return $this->success($result);
    }

    /**
     * 测试中间件
     * @param Request $request
     * @return \think\response\Json
     */
    public function testAuthLogin(Request $request)
    {
        $data = (new TokenService())->generateToken(110);
        return $this->success($data);
    }

    /**
     * 测试中间件
     * @param Request $request
     * @return \think\response\Json
     */
    public function testAuth(Request $request)
    {
        return $this->success($request->userId);
    }
}
